package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/sessions")
public class SessionController {

    @Autowired
    private IUserService userService;
    //登录
    /*
    *登录操作
    * 资源:/sessions
    * 动作:/POST
    * 参数:email:xx
    *     password:xx
    **/
    @PostMapping
    public Object login(@RequestParam String email, @RequestParam String password){
        JSONResult result = new JSONResult();
        try{
            //调用业务方法检验登录
            User u = userService.login(email,password);
            //把当前用户存入session中
            UserContext.setCurrentUser(u);
            //设置回调函数的返回参数
            result.setData(u);
        }catch (Exception e){
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
    *用户注销
    * 资源:/sessions
    * 动作:DELETE
    * 参数:
    **/
    @DeleteMapping
    public void logout(HttpSession session, HttpServletResponse resp){
        //销毁session
        session.invalidate();
        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
    }
}
